package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xn.app.muying.R;
import com.xn.app.muying.bean.OrderDoctor;
import com.xn.app.muying.bean.OrderDoctorScheduling;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AppConstant;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.DateUtils;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyImageLoader;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.RoundImageView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;

import okhttp3.Request;
import okhttp3.Response;

/**
 * 预约挂号-医生选择页面
 * Created by gaoge on 2016/11/22.
 */

public class OrderDoctorActivity extends BaseActivity implements View.OnClickListener {

    //星期选择
    private RadioGroup radiogroup = null;
    //标题
    private TextView title_name = null;
    //返回键
    private ImageView img_back = null;
    //上午
    private TextView am = null;
    //下午
    private TextView pm = null;
    //无数据显示页面
    private LinearLayout no_data_linearlayout = null;
    //数据显示页面
    private LinearLayout linearlayout = null;
    //数据显示列表
    private ListView listview = null;
    //记录科室ID
    private String departmentsID = "";
    //记录医院ID
    private String hospitalID = "";
    //记录科室名称
    private String departmentsName = "";
    //数据存储列表
    private ArrayList<OrderDoctor> doctorList = new ArrayList<>();
    private ArrayList<OrderDoctorScheduling> list = new ArrayList<>();
    //数据显示列表
    private ArrayList<OrderDoctor> doctorShowList = new ArrayList<>();
    //按钮存储
    private ArrayList<RadioButton> radioList = new ArrayList<>();
    //数据显示适配器
    private ListViewAdapter listviewAdapter = null;
    //数据库
    private DBManager db = null;
    //获取当前星期几
    private int today_week = 0;
    //加载框
    AlertDialog dialog;
    //获取用户选择的日期（周一到周五）
    private int week = 0;
    //获取用户选择的时间段（上午或者下午）
    private int allDay = 1;
    //获取用户当前选择的时间（年月日）
    private String timeData = null;
    Calendar now = Calendar.getInstance();
    /**
     * 图片缓存
     */
    private ImageLoader imageLoader = null;
    private DisplayImageOptions options = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_doctor);
        //初始化组件
        initialization();
        //实现
        realize();
    }

    /**
     * 初始化组件，并给相应控件添加单击事件
     * view
     */
    private void initialization() {
        db = new DBManager(this);
        imageLoader = MyImageLoader.getImageLoader(this);
        // DisplayImageOptions对象是对下载好以后的图片，在显示出来的时候做的设置
        options = new DisplayImageOptions.Builder().showImageOnLoading(0) // 在下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.doctor_no) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.doctor_no) // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565) // 防止内存溢出的，图片太多就这这个
                .cacheInMemory(true).cacheOnDisc(true).build();
        //获取当前星期几，日期为1234567 1代表星期天  2代表星期一  依次类推
        Calendar c = Calendar.getInstance();
        //-1后，为，日期为0123456 0代表星期天  1代表星期一  依次类推
        today_week = c.get(Calendar.DAY_OF_WEEK) - 1;
        //初始化组件
        radiogroup = (RadioGroup) findViewById(R.id.radiogroup);
        title_name = (TextView) findViewById(R.id.title_name);
        img_back = (ImageView) findViewById(R.id.img_back);
        am = (TextView) findViewById(R.id.am);
        pm = (TextView) findViewById(R.id.pm);
        no_data_linearlayout = (LinearLayout) findViewById(R.id.no_data_linearlayout);
        linearlayout = (LinearLayout) findViewById(R.id.linearlayout);
        listview = (ListView) findViewById(R.id.listview);
        //设置点击事件
        img_back.setOnClickListener(this);
        am.setOnClickListener(this);
        pm.setOnClickListener(this);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String name = db.select("name");
                String identityId = db.select("identityId");
                if (name != null && !name.equals("") && !name.equals("null")
                        && identityId != null && !identityId.equals("") && !identityId.equals("null")) {
                    Intent intent = new Intent(OrderDoctorActivity.this, OrderAffirmActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt("hospitalID", Integer.parseInt(hospitalID));
                    bundle.putInt("id", doctorShowList.get(i).getId());
                    bundle.putString("name", doctorShowList.get(i).getName());
                    bundle.putString("professionalTitle", doctorShowList.get(i).getProfessionalTitle());
                    bundle.putString("photoUrl", doctorShowList.get(i).getPhotoUrl());
                    bundle.putString("specialty", doctorShowList.get(i).getSpecialty());
                    bundle.putString("primaryDepartmentName", doctorShowList.get(i).getPrimaryDepartmentName());
                    bundle.putString("primaryHospitalName", doctorShowList.get(i).getPrimaryHospitalName());
                    bundle.putString("primaryHospitalLevel", doctorShowList.get(i).getPrimaryHospitalLevel());
                    bundle.putString("time", timeData);
                    bundle.putInt("allDay", allDay);
                    bundle.putInt("week", week);
                    bundle.putString("userName", db.select("name"));
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else {
                    //完善个人信息
                    Intent intent = new Intent(OrderDoctorActivity.this, PersonalActivity.class);
                    intent.putExtra("type", "1");
                    startActivity(intent);
                }
            }
        });
        //星期选择
        radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                listview.setVisibility(ListView.GONE);
                //按钮状态
                for (int i = 0; i < 5; i++) {
                    RadioButton tabrb = radioList.get(i);
                    if (tabrb.isChecked()) {
                        tabrb.setTextColor(getResources().getColor(R.color.white));
                        tabrb.setBackgroundResource(R.color.sys_fen);
                        try {
                            timeData = (now.get(Calendar.YEAR) + "." + tabrb.getText().toString().split("\n")[1]).replace(".", "-");
                        } catch (Exception e) {
                            ToastUtil.showToast(OrderDoctorActivity.this, "获取日期失败");
                        }
                    } else {
                        tabrb.setTextColor(getResources().getColor(R.color.sys_fen));
                        tabrb.setBackgroundResource(R.color.white);
                    }
                }
                //按钮点击事件
                switch (checkedId) {
                    //星期一
                    case R.id.monday_button:
                        week = 1;
                        break;
                    //星期二
                    case R.id.tuesday_button:
                        week = 2;
                        break;
                    //星期三
                    case R.id.wednesday_button:
                        week = 3;
                        break;
                    //星期四
                    case R.id.thursday_button:
                        week = 4;
                        break;
                    //星期五
                    case R.id.friday_button:
                        week = 5;
                        break;
                }
                //根据条件查询数据
                selectDoctor(week, allDay);
            }
        });
        //上午还是下午
        if (Integer.parseInt(DateUtils.getTime()) < 12) {
            allDay = 1;
        } else {
            allDay = 2;
        }

    }

    /**
     * 功能实现
     */
    private void realize() {
        //获取医院信息
        Intent intent = getIntent();
        departmentsID = intent.getStringExtra("id");
        departmentsName = intent.getStringExtra("name");
        hospitalID = intent.getStringExtra("hospitalID");
        //设置标题
        title_name.setText(departmentsName);
        //设置星期按钮
        for (int i = 0; i < 5; i++) {
            RadioButton tabrb = (RadioButton) radiogroup.getChildAt(i);
            radioList.add(tabrb);
        }
        //设置星期选项
        setData();
        //设置适配器
        listviewAdapter = new ListViewAdapter(OrderDoctorActivity.this, doctorShowList);
        listview.setAdapter(listviewAdapter);
        //获取数据
        if (NetworkUtil.isNetworkAvailable(this)) {
            dialog = new MyAlertDialog().ShowDialog(this, R.layout.dialog_loading);
            dialog.setCancelable(true);
            getData();
        }
    }

    /**
     * 设置星期按钮
     */
    private void setData() {
        //一天的时间戳  86400为一天的时间戳
        long oneDay = AppConstant.oneDay;
        //获取当前时间
        String time = DateUtils.getCurrentDate();
        //获取当前时间戳
        long timeNumber = DateUtils.getStringToDate2(time);
        //设置button按钮
        switch (today_week) {
            case 0:
                radioList.get(0).setText("周一\n" + DateUtils.getDateToStringMD(timeNumber + oneDay));
                radioList.get(1).setText("周二\n" + DateUtils.getDateToStringMD(timeNumber + oneDay * 2));
                radioList.get(2).setText("周三\n" + DateUtils.getDateToStringMD(timeNumber + oneDay * 3));
                radioList.get(3).setText("周四\n" + DateUtils.getDateToStringMD(timeNumber + oneDay * 4));
                radioList.get(4).setText("周五\n" + DateUtils.getDateToStringMD(timeNumber + oneDay * 5));
                break;
            case 1:
                radioList.get(0).setText("周一\n" + DateUtils.getDateToStringMD(timeNumber));
                radioList.get(1).setText("周二\n" + DateUtils.getDateToStringMD(timeNumber + oneDay));
                radioList.get(2).setText("周三\n" + DateUtils.getDateToStringMD(timeNumber + oneDay * 2));
                radioList.get(3).setText("周四\n" + DateUtils.getDateToStringMD(timeNumber + oneDay * 3));
                radioList.get(4).setText("周五\n" + DateUtils.getDateToStringMD(timeNumber + oneDay * 4));
                break;
            case 2:
                radioList.get(0).setText("周一\n" + DateUtils.getDateToStringMD(timeNumber - oneDay));
                radioList.get(1).setText("周二\n" + DateUtils.getDateToStringMD(timeNumber));
                radioList.get(2).setText("周三\n" + DateUtils.getDateToStringMD(timeNumber + oneDay));
                radioList.get(3).setText("周四\n" + DateUtils.getDateToStringMD(timeNumber + oneDay * 2));
                radioList.get(4).setText("周五\n" + DateUtils.getDateToStringMD(timeNumber + oneDay * 3));
                break;
            case 3:
                radioList.get(0).setText("周一\n" + DateUtils.getDateToStringMD(timeNumber - oneDay * 2));
                radioList.get(1).setText("周二\n" + DateUtils.getDateToStringMD(timeNumber - oneDay));
                radioList.get(2).setText("周三\n" + DateUtils.getDateToStringMD(timeNumber));
                radioList.get(3).setText("周四\n" + DateUtils.getDateToStringMD(timeNumber + oneDay));
                radioList.get(4).setText("周五\n" + DateUtils.getDateToStringMD(timeNumber + oneDay * 2));
                break;
            case 4:
                radioList.get(0).setText("周一\n" + DateUtils.getDateToStringMD(timeNumber - oneDay * 3));
                radioList.get(1).setText("周二\n" + DateUtils.getDateToStringMD(timeNumber - oneDay * 2));
                radioList.get(2).setText("周三\n" + DateUtils.getDateToStringMD(timeNumber - oneDay));
                radioList.get(3).setText("周四\n" + DateUtils.getDateToStringMD(timeNumber));
                radioList.get(4).setText("周五\n" + DateUtils.getDateToStringMD(timeNumber + oneDay));
                break;
            case 5:
                radioList.get(0).setText("周一\n" + DateUtils.getDateToStringMD(timeNumber - oneDay * 4));
                radioList.get(1).setText("周二\n" + DateUtils.getDateToStringMD(timeNumber - oneDay * 3));
                radioList.get(2).setText("周三\n" + DateUtils.getDateToStringMD(timeNumber - oneDay * 2));
                radioList.get(3).setText("周四\n" + DateUtils.getDateToStringMD(timeNumber - oneDay));
                radioList.get(4).setText("周五\n" + DateUtils.getDateToStringMD(timeNumber));
                break;
            case 6:
                radioList.get(0).setText("周一\n" + DateUtils.getDateToStringMD(timeNumber - oneDay * 5));
                radioList.get(1).setText("周二\n" + DateUtils.getDateToStringMD(timeNumber - oneDay * 4));
                radioList.get(2).setText("周三\n" + DateUtils.getDateToStringMD(timeNumber - oneDay * 3));
                radioList.get(3).setText("周四\n" + DateUtils.getDateToStringMD(timeNumber - oneDay * 2));
                radioList.get(4).setText("周五\n" + DateUtils.getDateToStringMD(timeNumber - oneDay));
                break;
        }
    }

    /**
     * 单击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //返回键
            case R.id.img_back:
                finish();
                break;
            //上午
            case R.id.am:
                listview.setVisibility(ListView.GONE);
                am.setTextColor(getResources().getColor(R.color.white));
                am.setBackgroundResource(R.drawable.red_left);
                pm.setTextColor(getResources().getColor(R.color.sys_fen));
                pm.setBackgroundResource(R.drawable.white_right);
                allDay = 1;
                //根据条件查询数据
                selectDoctor(week, allDay);
                break;
            //下午
            case R.id.pm:
                listview.setVisibility(ListView.GONE);
                pm.setTextColor(getResources().getColor(R.color.white));
                pm.setBackgroundResource(R.drawable.red_right);
                am.setTextColor(getResources().getColor(R.color.sys_fen));
                am.setBackgroundResource(R.drawable.white_left);
                allDay = 2;
                //根据条件查询数据
                selectDoctor(week, allDay);
                break;
        }
    }

    /**
     * 获取列表数据
     *
     * @return
     */
    public void getData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.OrderDoctor(departmentsID)).build();
                    Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    doctorList = new ArrayList<>();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 204 || code == 200) {
                        JSONArray items = new JSONArray(bodys);
                        for (int i = 0; i < items.length(); i++) {
                            JSONObject object = items.getJSONObject(i);
                            int id = object.optInt("id");
                            String name = object.optString("name");
                            String professionalTitle = object.optString("professionalTitle");
                            String photoUrl = object.optString("photoUrl");
                            String specialty = object.optString("specialty");
                            int priority = object.optInt("priority");
                            String primaryDepartmentName = object.optString("primaryDepartmentName");
                            String primaryHospitalName = object.optString("primaryHospitalName");
                            String primaryHospitalLevel = object.optString("primaryHospitalLevel");
                            //排班
                            String schedules = object.optString("schedules");
                            //填充数据
                            OrderDoctor bean = new OrderDoctor();
                            bean.setId(id);
                            bean.setName(name);
                            bean.setProfessionalTitle(professionalTitle);
                            bean.setPhotoUrl(photoUrl);
                            bean.setSpecialty(specialty);
                            bean.setPriority(priority);
                            bean.setPrimaryDepartmentName(primaryDepartmentName);
                            bean.setPrimaryHospitalName(primaryHospitalName);
                            bean.setPrimaryHospitalLevel(primaryHospitalLevel);
                            if (schedules != null && !schedules.equals("") && !schedules.equals("null")) {
                                list = new ArrayList<>();
                                JSONArray array = new JSONArray(schedules);
                                for (int a = 0; a < array.length(); a++) {
                                    JSONObject object1 = array.getJSONObject(a);
                                    String date = object1.optString("date");
                                    int week = object1.optInt("week");
                                    int time = object1.optInt("time");
                                    boolean isAvailable = object1.optBoolean("isAvailable");
                                    OrderDoctorScheduling bean1 = new OrderDoctorScheduling();
                                    bean1.setDate(date);
                                    bean1.setWeek(week);
                                    bean1.setTime(time);
                                    bean1.setAvailable(isAvailable);
                                    list.add(bean1);
                                }
                            }
                            bean.setSchedules(list);
                            doctorList.add(bean);
                        }
                        handler1.sendEmptyMessage(0);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        msg1.obj = "";
                        handler1.sendMessage(msg1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 接收线程返回的数据
     */
    Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (dialog != null) {
                dialog.dismiss();
            }
            switch (msg.what) {
                case 0:
                    //设置当天
                    if (today_week < 5) {
                        if (today_week == 0) {
                            week = 1;
                        } else {
                            week = today_week;
                        }
                        radioList.get(today_week).setChecked(true);
                        //上午还是下午
                        if (allDay == 1) {
                            am.setTextColor(getResources().getColor(R.color.white));
                            am.setBackgroundResource(R.drawable.red_left);
                            pm.setTextColor(getResources().getColor(R.color.sys_fen));
                            pm.setBackgroundResource(R.drawable.white_right);
                        } else {
                            pm.setTextColor(getResources().getColor(R.color.white));
                            pm.setBackgroundResource(R.drawable.red_right);
                            am.setTextColor(getResources().getColor(R.color.sys_fen));
                            am.setBackgroundResource(R.drawable.white_left);
                        }
                    } else {
                        listview.setVisibility(ListView.GONE);
                        no_data_linearlayout.setVisibility(LinearLayout.VISIBLE);
                    }
                    linearlayout.setVisibility(LinearLayout.VISIBLE);
                    break;
                case 1:
                    break;
            }
        }
    };

    /**
     * 查询符合条件的医生信息
     */
    private void selectDoctor(int week, int allDay) {
        doctorShowList = new ArrayList<>();
        for (int i = 0; i < doctorList.size(); i++) {
            list = doctorList.get(i).getSchedules();
            for (int a = 0; a < list.size(); a++) {
                int week1 = list.get(a).getWeek();
                int time = list.get(a).getTime();
                boolean isAvailable = list.get(a).getisAvailable();
                String year = list.get(a).getDate().split("T")[0];
                //如果时间一致
                if (year.equals(timeData)) {
                    //如果可以预约
                    if (isAvailable) {
                        //如果星期一致
                        if (week == week1) {
                            //如果时间段一致(上午，下午)
                            if (allDay == time) {
                                doctorShowList.add(doctorList.get(i));
                            }

                        }
                    }
                }
            }
        }
        if (doctorShowList != null && doctorShowList.size() > 0) {
            listviewAdapter.getData = doctorShowList;
            listviewAdapter.notifyDataSetChanged();
            listview.setSelection(0);
            listview.setVisibility(ListView.VISIBLE);
            no_data_linearlayout.setVisibility(LinearLayout.GONE);
        } else {
            listview.setVisibility(ListView.GONE);
            no_data_linearlayout.setVisibility(LinearLayout.VISIBLE);
        }
    }

    /**
     * 列表适配器
     */
    class ListViewAdapter extends BaseAdapter {
        LayoutInflater lf = null;
        ArrayList<OrderDoctor> getData = new ArrayList<>();
        ViewHolder viewHolder = null;

        public ListViewAdapter(Context context,
                               ArrayList<OrderDoctor> getData) {
            lf = LayoutInflater.from(context);
            this.getData = getData;
        }

        @Override
        public int getCount() {
            return getData.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @SuppressLint("InflateParams")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = lf.inflate(R.layout.order_doctor_item, null);
                viewHolder.relativelayout = (RelativeLayout) convertView.findViewById(R.id.relativelayout);
                viewHolder.image = (RoundImageView) convertView.findViewById(R.id.image);
                viewHolder.name = (TextView) convertView.findViewById(R.id.name);
                viewHolder.position = (TextView) convertView.findViewById(R.id.position);
                viewHolder.content = (TextView) convertView.findViewById(R.id.content);
                viewHolder.textview = (TextView) convertView.findViewById(R.id.textview);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.name.setText(getData.get(position).getName());
            viewHolder.position.setText(getData.get(position).getProfessionalTitle());
            if (!getData.get(position).getSpecialty().equals("") && !getData.get(position).getSpecialty().equals("null")) {
                viewHolder.content.setText(getData.get(position).getSpecialty());
            } else {
                viewHolder.content.setText("");
            }
            if (getData.get(position).getPhotoUrl() != null && !getData.get(position).getPhotoUrl().equals("") && !getData.get(position).getPhotoUrl().equals("null")) {
                imageLoader.displayImage(getData.get(position).getPhotoUrl(), viewHolder.image, options);
            } else {
                viewHolder.image.setImageResource(R.mipmap.doctor_no);
            }
            return convertView;
        }
    }

    /**
     * 包装类
     */
    private static class ViewHolder {
        private RelativeLayout relativelayout = null;
        private RoundImageView image = null;
        private TextView name = null;
        private TextView position = null;
        private TextView content = null;
        private TextView textview = null;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
